package com.AsyncDemo.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
public class ArticleService {
    // 查询文章
    public String selectArticle() {
        // TODO 模拟文章查询操作
        System.out.println("查询任务线程,线程名："+Thread.currentThread().getName());
        return "文章详情";
    }

    // 文章阅读量+1
    @Async
    public void updateReadCount() {
        // TODO 模拟耗时操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新任务线程,线程名："+Thread.currentThread().getName());
    }

    // 文章阅读量+1,指定线程池
    @Async("readCountExecutor")
    public void updateReadCountByExecutor() {
        // TODO 模拟耗时操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新任务线程,线程名："+Thread.currentThread().getName());
    }

    // 文章阅读量+1,指定线程池
    @Async("readCountNoReturnExecutor")
    public void updateReadCountNoReturnByExecutor() {
        // TODO 模拟耗时操作
        try {
            Thread.sleep(3000);
            int i = 1/0;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新任务线程,线程名："+Thread.currentThread().getName());
    }

    // 文章阅读量+1
    @Async("readCountExecutor")
    public CompletableFuture<Integer> updateReadCountHasResult() {
        // TODO 模拟耗时操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新文章阅读量线程"+Thread.currentThread().getName());
        return CompletableFuture.completedFuture(100 + 1);
    }
}
